package com.my.core.util.file;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;

public class FileUploadUtils {
//    @Override
//    public void imagesDownload(InsectMonitor insectMonitor) {
//        if (StringUtils.isNotBlank(insectMonitor.getImagesUrl())) {
//            String dateStr = DateUtils.yyyyMMdd.get().format(new Date());
//            String imagesName = insectMonitor.getAnalyseCoordUrl().substring(insectMonitor.getAnalyseCoordUrl().lastIndexOf("/") + 1);
//            String imagesPath = File.separator + IMAGES_TYPE + File.separator + dateStr;
//            File dir = new File(uploadPath + imagesPath);
//            if (!dir.exists()) {
//                if (!dir.mkdirs()) {
//                    log.error("下载虫情监测图片异常，无法创建目录: {}", dir.getAbsolutePath());
//                    return;
//                }
//            }
//            String savePath = dir.getPath() + File.separator + imagesName;
//            //如果已经下载 则直接返回
//            File imageFile = new File(savePath);
//            if (imageFile.exists()) {
//                return;
//            }
//            //图片下载
//            try {
//                FileUploadUtils.downloadImage(insectMonitor.getAnalyseCoordUrl(), savePath);
//                insectMonitor.setImagesPath(imagesPath + File.separator + imagesName);
//                log.info("虫情监测数据分析图片下载成功！");
//            } catch (IOException e) {
//                log.error("图片下载失败:{}", e.getMessage());
//            }
//        }
//    }

    /**
     * 文件下载
     *
     * @param imageUrl 下载路径
     * @param savePath 保存路径
     */
    public static void downloadImage(String imageUrl, String savePath) throws IOException {
        URL url = new URL(imageUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");

        // 添加请求头，模拟浏览器访问
        connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3");

        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
//            try (InputStream inputStream = connection.getInputStream();
//                 FileOutputStream outputStream = new FileOutputStream(savePath)) {
//
//                byte[] buffer = new byte[4096];
//                int bytesRead;
//                while ((bytesRead = inputStream.read(buffer)) != -1) {
//                    outputStream.write(buffer, 0, bytesRead);
//                }
//            }
            compressImage(connection.getInputStream(), savePath, 0.5f);
        } else {
            throw new IOException("HTTP请求失败，状态码：" + responseCode);
        }

        connection.disconnect();
    }


    /**
     * 图片压缩
     *
     * @param inputStream 输入流
     * @param outputPath  输出路径
     * @param quality     压缩质量（0.0f到1.0f之间，1.0f表示最高质量）
     * @throws IOException IO异常
     */
    public static void compressImage(InputStream inputStream, String outputPath, float quality) throws IOException {
        BufferedImage image = ImageIO.read(inputStream);

        Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("JPEG");
        if (!writers.hasNext()) {
            throw new IllegalStateException("No JPEG writer found");
        }

        ImageWriter writer = writers.next();
        ImageWriteParam param = writer.getDefaultWriteParam();
        param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        //0.0f到1.0f之间，1.0f表示最高质量
        param.setCompressionQuality(quality);

        try (FileOutputStream fos = new FileOutputStream(outputPath);
             ImageOutputStream ios = ImageIO.createImageOutputStream(fos)) {
            writer.setOutput(ios);
            writer.write(null, new IIOImage(image, null, null), param);
        } finally {
            writer.dispose();
        }
    }
}
